﻿using NB.MGJ.Common;
using NB.MGJ.Model;
using NB.MGJ.Model.Model;
using NB.MGJ.Service;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 用户管理相关
    /// </summary>
    /// =======================================================================
    /// 类名：ManagerController ManagerController的备注：ManagerController~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/08/30         华君                 新建<br/>
    /// 002           2017/09/05         华君                 经销商<br/>
    /// 003           2017/11/30         吕林                 修改<br/>
    /// =======================================================================<br/>
    public partial class ManagerController
    {
        public ActionResult Dealer()
        {
            return View();
        }
        //经销商下拉信息
        public JsonResult SelDistributorList(int SaleAreaId = 0, int disId = 0, int selfDisId = 0)
        {
            FleeGoodsService _mservice = new FleeGoodsService();
            List<AntiFleeing_Distributor> result = new List<AntiFleeing_Distributor>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                int _DisId = LogOnUser.Distributor;
                if (disId != 0) _DisId = disId;
                result = _mservice.GetDistributorService(SaleAreaId, _DisId, selfDisId);
            }
            else
            {
                result = _mservice.GetDistributorService(SaleAreaId, selfDisId);
            }
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem() { Text = "可选择", Value = "" });
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].Name, Value = result[i].Id.ToString() };
                if (disId == result[i].Id)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            // if (result.Count == 0) items.Add(new SelectListItem() { Text = "无", Value = " " });
            return Json(items);
        }
        //经销商等级下拉信息
        public JsonResult SelDiscLevelList(int DistributorId = 0, int levelId = 0)
        {
            var result = new List<AntiFleeing_DistributorLevel>();

            if (DistributorId != 0)//经销商
            {
                result = _mservice.SelDiscLevel(DistributorId, LogOnUser.EnterpriseId);
            }
            else
            {
                if (LogOnUser.Distributor != 0)
                {
                    result = _mservice.SelDiscLevel(LogOnUser.Distributor, LogOnUser.EnterpriseId);
                }
                else result = _mservice.SelDiscLevel(LogOnUser.EnterpriseId);
            }
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].LevelName, Value = result[i].Id.ToString() };
                if (levelId == result[i].Id)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            if (result.Count == 0) items.Add(new SelectListItem() { Text = "请选择", Value = "" });
            return Json(items);
        }
        /// <summary>
        /// 管瞎区域和跨区域下拉信息
        /// </summary>
        /// <param name="id">上级区域Id</param>
        /// <param name="Ids">对应区块的上级经销的区域Id</param>
        /// <param name="DisId">上级经销商Id</param>
        /// <param name="type">区域数据加载类型</param>
        /// 1 市级数据的加载 2 区/县数据的加载
        /// <param name="acrossType">下拉框数据加载类型</param>
        /// acrossType: 0 管辖区域下拉框数据的加载 1 跨片区下拉框加载
        /// <returns></returns>
        public JsonResult GetPrivance(string id, string Ids, string DisId = null, string type = null, string acrossType = null)
        {
            var model = new List<PCRModel>();
            if (string.IsNullOrWhiteSpace(DisId) || DisId == "null")
            {
                if (LogOnUser.Distributor != 0)//经销商
                {
                   // AntiFleeing_Distributor model0 = _mservice.DiscGetModel(LogOnUser.Distributor.ToString());
                    //var ids = model0.JurisdictionCity + "," + model0.JurisdictionRegion + "," + model0.AcrossCity + "," + model0.AcrossRegion
                    // + "," + model0.JurisdictionPrivance + "," + model0.AcrossPrivance;
                    // model = _comservice.GetPCRModelAll(id).Where(obj => ids.Contains(obj.codeID)).ToList();  
                    model = PCRModel(LogOnUser.Distributor.ToString(), id, type, acrossType);   
                }
                else
                {
                    model = _comservice.GetPCRModelAll(id);
                }
            }
            else
            {
                model = PCRModel(DisId, id, type, acrossType); 
            }
            List<SelectListItem> shi = new List<SelectListItem>();
            if (model!=null)
            {
                foreach (var item in model)
                {
                    shi.Add(new SelectListItem { Value = item.codeID, Text = item.name, Selected = (Ids.Contains(item.codeID)) });
                }
            }
            return Json(shi);
        }
        public List<PCRModel> PCRModel(string DisId, string id, string type,string acrossType)
        {
            var model = new List<PCRModel>();
            AntiFleeing_Distributor model0 = _mservice.DiscGetModel(DisId);
            model = _comservice.GetPCRModelAll(id);
            if (type == null)
            {
                model = model.Where(obj => model0.JurisdictionPrivance.Contains(obj.codeID)).ToList();
            }
            else if (type == "1")
            {
                if (acrossType=="0")
                {
                    if (model0.JurisdictionCity != "null")
                        model = model.Where(obj => model0.JurisdictionCity.Contains(obj.codeID)).ToList(); 
                }
                else
                {
                      if (model0.AcrossCity != "null")
                          model = model.Where(obj => model0.AcrossCity.Contains(obj.codeID)).ToList();
                } 
            }
            else
            {
                if (acrossType == "0")
                {
                    if (model0.JurisdictionRegion != "null")
                        model = model.Where(obj => model0.JurisdictionRegion.Contains(obj.codeID)).ToList();
                }
                else
                {
                    if (model0.AcrossRegion != "null")
                        model = model.Where(obj => model0.AcrossRegion.Contains(obj.codeID)).ToList();
                }

            }
            return model;
        }
        public JsonResult Privance(string id, string ids)
        {
            var model = new List<PCRModel>();
            model = _comservice.GetPCRModelAll(id);
            if (ids == null) ids = "0";
            List<SelectListItem> sheng = new List<SelectListItem>();
            foreach (var item in model)
            {
                sheng.Add(new SelectListItem { Value = item.codeID, Text = item.name, Selected = (ids.Contains(item.codeID)) });
            }
            return Json(sheng);
        }
        public ActionResult DealerShowData(int id)
        {
            var model = _mservice.DealerShowDataId(id);
            ViewBag.or = model;
            return View();
        }
        //增加或编辑经销商
        public ActionResult AEdit(int id = 0)
        {
            var disc = _mservice.DiscGetModel(id.ToString());
            // var level = new List<AntiFleeing_DistributorLevel>();
            //if (LogOnUser.Distributor != 0)//经销商
            //{
            //    //经销商等级
            //    level = _mservice.SelDiscLevel(LogOnUser.Distributor, LogOnUser.EnterpriseId);
            //    // var   disc = _mservice.DiscGetModel(LogOnUser.Distributor.ToString());
            //}
            //else
            //{
            //    //经销商等级
            //    level = _mservice.SelDiscLevel(LogOnUser.EnterpriseId);
            //}
            if (disc == null)
            {
                disc = new AntiFleeing_Distributor();
                disc.JurisdictionPrivance = "0";
                disc.AcrossPrivance = "0";
                disc.Province = 0;
            }
            List<SelectListItem> items = new List<SelectListItem>();
            //for (int i = 0; i < level.Count; i++)
            //{
            //    SelectListItem item = new SelectListItem() { Text = level[i].LevelName, Value = level[i].Id.ToString() };
            //    if (disc.LevelID == level[i].Id)
            //    {
            //        item.Selected = true;
            //    }
            //    items.Add(item);
            //}

            ViewData["LevelID"] = items;
            FleeGoodsController fleegoods = new FleeGoodsController();
            ViewData["SaleAreaId"] = fleegoods.SelSaleAreaList(disc.SalesAreaID ?? 0);
            return View(disc);
        }
        public List<SelectListItem> GetDuoXuanShi(string id)
        {
            var result = _hhservice.GetDuoXuanShiService(id);
            return result;
        }
        #region 经销商
        //经销商信息分页查询
        public ActionResult DiscPageList(string key,int eId, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                // pm.StrCondition = " w.CreateLoginID=" + LogOnUser.UserID;
                pm.StrCondition = string.Format("  FIND_IN_SET(w.ID,getDiscChild({0})) and ID!={0}", LogOnUser.Distributor);

            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                    {
                        pm.StrCondition = " (w.EnterpriseId  in (0))";
                    }
                    else
                    {
                        pm.StrCondition = " (w.EnterpriseId in (" + LogOnUser.JuniorEnterprise + "))";
                    }
                }
                else
                {
                    pm.StrCondition = "1=1";
            
                }
            }
             pm.StrCondition += eId != 0
             ? " and w.EnterpriseId=" + eId
             : "";
             return Json(_mservice.DiscGetPageList(ref pm, key));
        }
        /// <summary>
        /// 导出EXCEL
        /// Pass 1
        /// </summary>
        public ActionResult ExportDealer(string key)
        {
            var model = _mservice.GetAllDealer(key);
            var _byte_catch = Excel.Exprot<V_Distributor>(model.ToList(), new string[] { "所属机构", "经销商名称", "联系人", "联系手机", "经销商等级", "所属片区", "管辖区域", "管辖省", "管辖市", "管辖区（县）", "所跨省", "所跨市", "所跨区（县）", "联系电话" }, q =>
            {
                return new object[] { 
		               q.EnterpriseName,
		               q.Name,
		               q.Contacts,
		               q.ContactMobile,
		               q.DisLevelName,
		               q.SalesArea,
		               q.JurisdictionPrivanceName,
                       q.JurisdictionCityName,
                       q.JurisdictionRegionName,
                       q.AcrossPrivanceName,
                       q.AcrossCityName,
                       q.AcrossRegionName,
		               q.ContactsTel,
				};
            }, "Dealer");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        //导入经销商信息
        public ActionResult Import(string filePath)
        {
            try
            {
                DataTable dt = Excel.ExcelToDataTable(filePath, true);
                if (dt!=null)
                {
                    dt.Columns["经销商名称"].ColumnName = "Name";
                    dt.Columns["经销商地址"].ColumnName = "Address";
                    dt.Columns["管辖省"].ColumnName = "JurisdictionPrivanceName";
                    dt.Columns["管辖市"].ColumnName = "JurisdictionCityName";
                    dt.Columns["管辖区（县）"].ColumnName = "JurisdictionRegionName";
                    dt.Columns["所属片区"].ColumnName = "SalesAreaName";
                    dt.Columns["联系人"].ColumnName = "Contacts";
                    dt.Columns["电话"].ColumnName = "ContactMobile";
                    dt.Columns["上级经销商编号"].ColumnName = "ParentId";//antifleeing_distributor
                    //机构Id
                    DataColumn _newColum = new DataColumn();
                    _newColum.DataType = System.Type.GetType("System.Int32");//该列的数据类型 
                    _newColum.ColumnName = "EnterpriseId";//该列得名称 
                    _newColum.DefaultValue = LogOnUser.EnterpriseId;//该列得默认值 
                    dt.Columns.Add(_newColum);
                    //创建人
                    DataColumn _CreateBy = new DataColumn();
                    _CreateBy.DataType = System.Type.GetType("System.Int32");//该列的数据类型 
                    _CreateBy.ColumnName = "CreateLoginID";//该列得名称 
                    _CreateBy.DefaultValue = LogOnUser.UserID;//该列得默认值 
                    dt.Columns.Add(_CreateBy);
                    //创建时间
                    DataColumn _CreateTime = new DataColumn();
                    _CreateTime.DataType = System.Type.GetType("System.DateTime");//该列的数据类型 
                    _CreateTime.ColumnName = "CreateDate";//该列得名称 
                    _CreateTime.DefaultValue = DateTime.Now;//该列得默认值 
                    dt.Columns.Add(_CreateTime);
                    //创建人登陆名
                    DataColumn _CreateByName = new DataColumn();
                    _CreateByName.DataType = System.Type.GetType("System.String");//该列的数据类型 
                    _CreateByName.ColumnName = "CreateLoginName";//该列得名称 
                    _CreateByName.DefaultValue = LogOnUser.LoginName;//该列得默认值 
                    dt.Columns.Add(_CreateByName);

                    FleeGoodsService _flee = new FleeGoodsService();
                    _flee.ExecuteOfBatch(dt, "antifleeing_distributor_temp");
                    //开始导入
                    string str = _mservice.BatchImport_Dic_Excel();
                    if (string.IsNullOrEmpty(str))
                    {
                        return Json("导入成功！");
                    }
                    else return Json("第 " + str + " 列存在联系方式重复或数据异常的问题，在导入时系统已自动排除该项！");
                }else return Json("文件不能为空");

              
            }
            catch (Exception ex)
            {

                return Json(ex.Message);
            }


        }
        public ActionResult DiscSaveDate(L.EntityModel.AntiFleeing_Distributor model)
        {  //判断经销商名称和手机号唯一性
            //  bool IsExist = _mservice.ExistDictributor(model.Name, model.ContactMobile, LogOnUser.EnterpriseId, model.Id.Value);
            //   if (!IsExist) return Json("-1");
            if (model.Id == null)//新增
            {
                model.EnterpriseId = LogOnUser.EnterpriseId;
                model.CreateDate = DateTime.Now;
                model.CreateLoginID = LogOnUser.UserID;
                model.CreateLoginName = LogOnUser.LoginName;
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = LogOnUser.UserID;
                model.ChangeLoginName = LogOnUser.LoginName;
                if (model.ParentId == null)
                {
                    model.ParentId = LogOnUser.Distributor;
                }
                model.ViewDel = 0;//枚举是否删除
                int id = _mservice.DiscAdd(model);
                if (id <= 0) return Json(id);
                //新增用户
                Sys_User sysUModel = new Sys_User();
                sysUModel.LoginName = model.ContactMobile;//手机号
                sysUModel.Pwd = "49BA59ABBE56E057";
                sysUModel.EnterpriseId = LogOnUser.EnterpriseId;
                sysUModel.RealName = model.Name;
                sysUModel.Modile = model.ContactMobile;
                sysUModel.DisableTime = null;
                sysUModel.Distributor = id;
                sysUModel.ChangeDate = DateTime.Now;
                sysUModel.ChangeLoginID = LogOnUser.UserID;
                sysUModel.ChangeLoginName = LogOnUser.LoginName;
                sysUModel.ViewDel = 0;
                sysUModel.ViewFlag = 1;//启用
                int i = _mservice.AddUserInfoService(sysUModel);
                //关联角色
                string sql = string.Format("insert into sys_roleuserinfo(rid,uId)VALUES(8,{0});", i);
                _mservice.RelationRole(sql);
                return Json(i);
            }
            else
            {
                model.CreateDate = DateTime.Now;
                model.CreateLoginID = LogOnUser.UserID;
                model.CreateLoginName = LogOnUser.LoginName;
                model.ViewDel = 0;
                model.EnterpriseId = LogOnUser.EnterpriseId;
                int j = _mservice.DiscUpdate(model);
                return Json(j);
            }
        }
        //手机号是否重复
        public JsonResult CheckDealerName(string Name, string ContactMobile, int id = 0)
        {
            bool isExist = true;
            isExist = _mservice.ExistDictributor(Name, ContactMobile, LogOnUser.EnterpriseId, id);
            if (isExist) isExist = _mservice.GetByUserName(ContactMobile);
            return Json(new
            {
                valid = isExist
            });
        }
        public ActionResult DiscDel(int? id = 0)
        {

            L.EntityModel.AntiFleeing_Distributor model = new L.EntityModel.AntiFleeing_Distributor();
            model.Id = id;
            model.ViewDel = 1;//删除
            int i = _mservice.DiscUpdate(model, 1);

            return Json(i);
        }
        public ActionResult DealerInfo(int? id = 0)
        {
            var model = _mservice.DiscGetInfo(id.ToString());
            ViewBag.model = model;
            return View(model);
        }
        #endregion
        //增加或编辑经销商等级管理
        public ActionResult AEditLevel()
        {
            return View();
        }

        public ActionResult ExportDemo()
        {
            string fileUrl = @"~\UploadFile\经销商导入格式模板.xlsx";
            return File(new FileStream(Server.MapPath(fileUrl), FileMode.Open), "application/octet-stream", Server.UrlEncode("经销商导入格式模板.xlsx"));
        }


        #region 片区

        /// <summary>
        /// 获取片区列表
        /// </summary>
        public ActionResult GetAreaManagerList(int pageIndex, int pageSize, string searchKey)
        {
            var r = new PagerModel
            {
                PageSize = pageSize,
                Page = pageIndex
            };
            return Json(_mservice.GetSaleAreaList(searchKey, ref r, LogOnUser));
        }


        /// <summary>
        /// 片区导出
        /// </summary>
        public ActionResult AreaExcelExport(string key)
        {
            var _file_ = Excel.Exprot<AntiFleeing_SalesArea>(_mservice.GetSaleAreaList(key),
                  new string[] { "片区名称", "联系人", "联系电话", "创建时间" },
                  p =>
                  {
                      return new object[] { 
                         p.Name,
                         p.Contacts,
                         p.ContactTel,
                         p.CreateDate
                    };
                  }, "AreaSheet");
            return File(_file_, "application/octet-stream", string.Format("{0}.xlsx", Guid.NewGuid().ToString()));
        }
        public ActionResult DeleteAreaManager(int id)
        {
            return Json(_mservice.DeleteAreaManager(id));
        }

        //增加或编辑片区管理
        public ActionResult AEditArea(int? id = null)
        {
            var model = new AntiFleeing_SalesArea();
            if (id.HasValue)
            {
                model = _mservice.GetSaleAreInfo(id.Value);
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult EditAreaSave(AntiFleeing_SalesArea model)
        {
            if (model == null)
            {
                throw new Exception("当前无法执行该操作");
            }
            model.ChangeDate = DateTime.Now;
            model.ChangeLoginID = LogOnUser.UserID;
            model.ChangeLoginName = LogOnUser.LoginName;
            return Json(_mservice.UpdateSlaeArea(model));
        }


        [HttpPost]
        public ActionResult AddAreaSave(AntiFleeing_SalesArea model)
        {
            if (model == null)
            {
                throw new Exception("当前无法执行该操作");
            }
            model.CreateDate = DateTime.Now;
            model.EnterpriseId = LogOnUser.EnterpriseId;
            model.CreateLoginID = LogOnUser.UserID;
            model.CreateLoginName = LogOnUser.LoginName;
            model.ViewDel = 0;
            return Json(_mservice.AddSaleArea(model));
        }
        #endregion

    }
}